#include <iostream>
#include <string.h>
#include<stdio.h>
using namespace std;

struct Str{
    char *ch;
    int length;
};

void init(Str &T){
    T.ch=nullptr;
    T.length=0;
}

int strAssign(Str &str,char *ch)
{
    if (str.ch) {
        delete str.ch;
    }
    char *c=ch;
    while (*c)  //求ch串长度
    {
        ++str.length;
        ++c;
    }
    if(str.length==0)
    {
        str.ch= nullptr;
        str.length=0;
        return 1;
    }
    else
    {
        str.ch=new char(str.length+1);
        if (str.ch== nullptr)
            return 0;
        else
        {
            strcpy(str.ch, ch);
            return 1;
        }
    }
}

/*void Concat(Str &T,Str T1,Str T2){
    
    T.length=T1.length+T2.length;
    T.ch=new char(T.length+1);
    int i,j;
    for (i=0; i<T1.length; i++) {
        T.ch[i]=T1.ch[i];
    }
    for (j=0; j<T2.length; j++) {
        T.ch[i+j]=T2.ch[j];
    }
    
}*/

int Concat(Str &T,Str T1,Str T2){
    if (T.ch) {
        delete T.ch;
    }
    if (T1.length+T2.length<=Maxsize) {
        int i,j;
        for (i=0; i<T1.length; i++) {
            T.ch[i]=T1.ch[i];
        }
        for (j=0; j<T2.length; j++) {
            T.ch[i+j]=T2.ch[j];
        }
        T.length=T1.length+T2.length;
        return 1;
    }
    else if(T1.length<Maxsize){
        int i,j;
        for (i=0; i<T1.length; i++) {
            T.ch[i]=T1.ch[i];
        }
        for (j=0; i+j<Maxsize; j++) {
            T.ch[i+j]=T2.ch[j];
        }
        cout<<"The Str is full"<<endl;
        T.length=Maxsize;
        return 0;
    }
    else{
        int i;
        for (i=0; i<Maxsize; i++) {
            T.ch[i]=T1.ch[i];
        }
        cout<<"The Str is full"<<endl;
    }
    T.length=Maxsize;
    return 0;
}

int SubString(Str &Sub,Str S,int pos,int len){
    if (pos<1||len<1||pos>S.length||len>S.length-pos+1) {
        Sub.length=0;
        return 0;
    }
        for (int i=0; i<len; i++) {
            Sub.ch[i]=S.ch[pos+i];
        }
        Sub.length=len;
    return 1;
}

int main(int argc, const char * argv[]) {
    // insert code here...
    Str T;
    init(T);
    char ch[]="China";
    strAssign(T,ch);
    Str data1,data2;
    init(data1);
    init(data2);
    char b[]="China ";
    char c[]="is very good!";
    Str sub;
    init(sub);
    strAssign(data1, b);
    strAssign(data2, c);
    Concat(T, data1, data2);
    cout<<"The length is :"<<T.length<<endl;
    cout<<"The data is :"<<T.ch<<endl;
    SubString(sub, T, 3, 5);
    cout<<"The sub of length is"<<sub.length<<endl;
    cout<<"The sub of data is"<<sub.ch<<endl;
    return 0;
}
